<template>
    <el-card>
        <div slot="header">
            <el-input
                    placeholder="搜索 ID / 用户名 / 邮箱 / 手机"
                    prefix-icon="el-icon-search"
                    v-model="search"
                    clearable
                    style="width: 240px">
            </el-input>
            <el-button @click="create()" type="primary">新建账号</el-button>
        </div>
        <el-table :data="user"
                  :v-loading="loading"
                  @filter-change="userLevelFilter"
                  @row-click="open">
            <el-table-column label="ID" width="60">
                <template slot-scope="scope">
                    <span v-text="scope.row.id"></span>
                </template>
            </el-table-column>
            <el-table-column
                    label="用户级别"
                    prop="level.name"
                    column-key="level"
                    :filters="level"/>
            <el-table-column label="用户名" prop="username"/>
            <el-table-column label="邮箱" prop="email"/>
            <el-table-column label="手机" prop="phone"/>
            <el-table-column label="注册时间" prop="created_at"/>
        </el-table>
        <el-pagination
                background
                layout="prev, pager, next"
                :page-size="$store.state.pageSize"
                :current-page.sync="page"
                @current-change="fetch"
                :total="total">
        </el-pagination>
        <el-dialog :title="view.title" :visible.sync="view.visible">
            <el-form :model="view.user" :rules="rules" ref="view" label-width="100px" status-icon>
                <el-form-item label="账号" prop="username">
                    <el-input v-model="view.user.username" auto-complete="off" placeholder="可以填入中文，最少4位"/>
                </el-form-item>
                <el-form-item label="手机号码" prop="phone">
                    <el-input v-model="view.user.phone" auto-complete="off" placeholder="11位手机号码"/>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="view.user.email" placeholder="邮箱地址"/>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input type="password" v-model="view.user.password" auto-complete="off"
                              placeholder="最少6位"/>
                </el-form-item>
                <el-form-item label="确认密码" prop="checkPassword">
                    <el-input type="password" v-model="view.user.checkPassword" auto-complete="off"
                              placeholder="确认密码一致性"/>
                    <el-alert type="warning" title="不修改密码，请将两个密码输入框留空"/>
                </el-form-item>
                <el-form-item label="禁止登录到">
                    <el-date-picker v-model="view.user.disable" type="datetime"/>
                    <br>时间到期后可登录
                </el-form-item>
                <el-form-item v-if="view.message.show">
                    <el-alert :title="view.message.content" :type="view.message.type"/>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="view.visible = false">取 消</el-button>
                <el-button type="primary" @click="view.submit()" :loading="view.loading">
                    {{view.type === 'edit' ? '编辑' :'新建' }}
                </el-button>
            </div>
        </el-dialog>
    </el-card>
</template>

<script>
    import _ from 'lodash';

    const emptyMessage = {type: '', content: '', show: false,};
    const emptyView = {
        visible: false,
        loading: false,
        type: 'edit',
        title: '',
        message: Object.assign({}, emptyMessage),
        user: {
            username: '',
            phone: '',
            email: '',
            password: '',
            checkPassword: '',
            disable: null,
        },
        submit: () => {
        },
    };
    export default {
        data() {
            return {
                total: 0,
                page: 1,
                loading: true,
                level: [],
                user: [],
                view: Object.assign({}, emptyView),
                rules: {
                    username: [{
                        validator: (rule, value, callback) => {
                            if (_.isEmpty(value))
                                return callback(new Error('请输入账号'));
                            if (value.length >= 4)
                                return callback();
                            callback(new Error('账号最少4位'));
                        }, trigger: 'blue, change'
                    }],
                    phone: [{
                        validator: (rule, value, callback) => {
                            if (_.isEmpty(value))
                                return callback(new Error('请输入手机号码'));
                            if (value.length === 11 && value.indexOf(1) === 0)
                                return callback();
                            callback(new Error('不符合手机号码格式'));
                        }, trigger: 'blue, change'
                    }],
                    email: [{
                        validator: (rule, value, callback) => {
                            if (_.isEmpty(value))
                                return callback(new Error('请输入邮箱'));
                            if (value.match(/[a-z0-9][a-z0-9._]*@[a-z0-9]+\.[a-z]{2,}/i))
                                return callback();
                            callback(new Error('不符合邮箱格式'));
                        }, trigger: 'blue, change'
                    }],
                    password: [{
                        validator: (rule, value, callback) => {
                            const type = this.view.type;

                            if (type === 'edit') {
                                if (_.isEmpty(value) && _.isEmpty(this.view.user.checkPassword))
                                    return callback();
                            }

                            if (value.length < 6)
                                callback(new Error('密码最少6位'));
                            else
                                callback();
                        }, trigger: 'blue, change'
                    }],
                    checkPassword: [{
                        validator: (rule, value, callback) => {
                            const type = this.view.type;

                            if (type === 'edit') {
                                if (_.isEmpty(value) && _.isEmpty(this.view.user.password))
                                    return callback();
                            }

                            if (value !== this.view.user.password)
                                callback(new Error('两个密码不一致'));
                            else
                                callback();

                        }, trigger: 'blue, change'
                    }],
                },
                search: '',
            };
        },
        methods: {
            fetch(data) {
                this.loading = true;
                const params = {page: this.page};
                if (data && data.level)
                    params.level = data.level.join(',');
                if (!_.isEmpty(this.search))
                    params.search = this.search;
                this.$http.get('/api/user', {params}).then(res => {
                    res.data.list.forEach(user => {
                        user.created_at = moment(user.created_at).calendar();
                    });
                    this.user = res.data.list;
                    this.total = res.data.total;
                    this.page = res.data.page;
                    this.loading = false;
                });
            },
            userLevelFilter(value) {
                this.fetch(value);
            },
            open(row, e, column) {
                if (row.id === 1)
                    return this.$alert('不能编辑 系统 账号');

                this.view = Object.assign({}, emptyView);
                this.view.user = row;
                this.view.title = '编辑账号 ' + row.username;
                this.view.type = 'edit';
                this.view.visible = true;
                this.view.submit = () => {
                    this.$refs['view'].validate((valid) => {
                        if (!valid) return;
                        this.view.loading = true;
                        this.view.message = Object.assign({}, emptyMessage);
                        this.$http.put('/api/user/' + row.id, this.view.user).then(res => {
                            this.view.loading = false;
                            this.view.message.show = true;
                            this.view.message.type = 'success';
                            this.view.message.content = '编辑成功';
                        }).catch(res => {
                            this.view.loading = false;
                            this.view.message.show = true;
                            this.view.message.type = 'error';
                            this.view.message.content = res.response.data;
                        });
                    });
                };
            },
            create() {
                this.view = Object.assign({}, emptyView);
                this.view.title = '新建账号';
                this.view.type = 'new';
                this.view.visible = true;
                this.view.submit = () => {
                    this.$refs['view'].validate((valid) => {
                        if (!valid) return;
                        this.view.loading = true;
                        this.view.message = Object.assign({}, emptyMessage);
                        this.$http.post('/api/user', this.view.user).then(res => {
                            this.view.loading = false;
                            this.view.message.show = true;
                            this.view.message.type = 'success';
                            this.view.message.content = '新建成功';
                            this.fetch();
                        }).catch(res => {
                            this.view.loading = false;
                            this.view.message.show = true;
                            this.view.message.type = 'error';
                            this.view.message.content = res.response.data;
                        });
                    });
                };
            },
        },
        watch: {
            search: _.debounce(function () {
                this.fetch();
            }, 500),
        },
        mounted() {
            this.fetch();
            this.$http.get('/api/user_level').then(res => {
                this.level = res.data.map(level => {
                    return {text: level.name, value: level.id};
                });
            });
        }
    }
</script>

<style scoped>

</style>